package com.imchenio.utils.log;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@Aspect
@Slf4j
public class CallingLogAspect {

    @Pointcut("@annotation(com.imchenio.utils.log.EnableCallingLog)")
    public void targetAnnotation() {
    }

    @Before(value = "targetAnnotation()")
    public void before(JoinPoint joinPoint) {
        if (joinPoint == null) {
            return;
        }

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();

        Object[] args = joinPoint.getArgs();

        log.debug("Calling Log——method={}, args={}", method.getName(), args);
    }

    @AfterReturning(value = "targetAnnotation()", returning = "returnObject")
    public void afterReturning(JoinPoint joinPoint, Object returnObject) {
        log.debug("Calling Log——return={}", returnObject);
    }

    @AfterThrowing(value = "targetAnnotation()", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Throwable e) {
        log.debug("Calling Log——Fail!");
    }
}
